#include "CameraShaker.h"
#include "OgreStringConverter.h"

CameraShaker::CameraShaker(Ogre::Camera * camera, Ogre::Real xAmplitude, Ogre::Real yAmplitude, Ogre::Real xFrequency, Ogre::Real yFrequency, Ogre::Real animTime) {
	mCamera = camera;
	xBaseAmplitude = xAmplitude;
	yBaseAmplitude = yAmplitude;
	xMFrequency = xFrequency;
	yMFrequency = yFrequency;
	timePassed = 0;
	timeToWait = 0;
	animationTime = animTime;
	started = false;
}

CameraShaker::~CameraShaker(void) {}

void CameraShaker::shakeCamera(Ogre::Real timeElapsed) {
	if(started) {
		timeToWait -= timeElapsed;
		if(timeToWait <= 0) {
			if(timePassed >= animationTime) {
				timeToWait = 0;
				started = false;
				return;
			}
			Ogre::Real xVarAmplitude = interpolate(timePassed,xBaseAmplitude);
			Ogre::Real yVarAmplitude = interpolate(timePassed,yBaseAmplitude);
			Ogre::Real xVarFrequency = interpolate(timePassed,xMFrequency);
			Ogre::Real yVarFrequency = interpolate(timePassed,yMFrequency);
			
			mCamera->yaw(Ogre::Radian(Ogre::Degree(xVarAmplitude * Ogre::Math::Sin((timePassed)*xMFrequency))));
			mCamera->pitch(Ogre::Radian(Ogre::Degree(yVarAmplitude * Ogre::Math::Sin((timePassed)*yMFrequency))));
			timePassed += timeElapsed;
		}
	}
}

Ogre::Real CameraShaker::interpolate(Ogre::Real time,Ogre::Real value) {
	Ogre::Real a = 1.0/(animationTime*0.5);
	return value * (- Ogre::Math::Pow((a*time) - 1,2) + 1);
}

bool CameraShaker::isActive() { return started; }

void CameraShaker::startCameraShake(Ogre::Real timeWait) {
	timeToWait = timeWait;
	timePassed = 0;
	started = true;
}